from django.db import models
from tinymce import models as tinymce_models
from django.core.urlresolvers import reverse
from thumbs import ImageWithThumbsField

class GeoField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 50
        kwargs['default'] = '36.97417,-122.030811'
        super(GeoField, self).__init__(*args, **kwargs)

def image_upload_to(instance, filename):
    return 'scpl/' + instance.__class__.__name__ + '/' + instance.slug + '/' + filename

class BaseContent(models.Model):
    class Meta:
        abstract = True
    name = models.CharField(max_length=50, unique=True)
    content = tinymce_models.HTMLField()
    slug = models.SlugField(max_length=16, primary_key=True)
    image = ImageWithThumbsField(max_length=200, upload_to=image_upload_to, sizes=((50,50),(125,125),(300,300)))
    last_update = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.name
        
class Landmark(BaseContent):
    target_url = models.URLField(max_length=300, verbose_name = 'Target URL')
    location = GeoField()
    def get_absolute_url(self):
        return reverse('landmark-detail', kwargs={'pk':self.slug})

class Tag(BaseContent):
    TYPE_CHOICES = (
        ('T', 'Tour'),
        ('O', 'Topic'),
        ('E', 'Era'),
        ('P', 'Person'),
        ('A', 'Tag'),
    )
    tag_type = models.CharField(max_length=1, choices=TYPE_CHOICES)
    main_landmark = models.ForeignKey('Landmark', blank=True, null=True)

    def get_absolute_url(self):
        if self.tag_type == 'T':
            viewtype = 'tour'
        elif self.tag_type == 'O':
            viewtype = 'topic'
        elif self.tag_type == 'E':
            viewtype = 'era'
        elif self.tag_type == 'P':
            viewtype = 'person'
        else:
            viewtype = 'tag'

        return reverse(viewtype + '-detail', kwargs={'pk':self.slug})

    def __unicode__(self):
        if self.tag_type == 'T':
            t = 'Tour'
        elif self.tag_type == 'O':
            t = 'Topic'
        elif self.tag_type == 'P':
            t = 'Person'
        elif self.tag_type == 'E':
            t = 'Era'
        else:
            t = 'Tag'
        return "%s (%s)" % (self.name, t)

class LandmarkTag(models.Model):
    tag = models.ForeignKey('Tag')
    landmark = models.ForeignKey('Landmark')
    priority = models.IntegerField(default = 0)

    def __unicode__(self):
        return "%s - %s [%d]" % (self.landmark, self.tag, self.priority)
